import { action, observable, toJS, computed, asMap } from 'mobx';
import { message } from 'antd';
import Actions from './actions';
import ReplyStore from '../reply';
import _ from 'lodash';
import window, { replaceE8Url } from '../../util';
import DetailImportStore from './DetailImport';
import $ from "jquery";
import { layoutBase, mainFields, initDetail, getDetailFields, getModeBase, checkCardRight, getWaterMarkImg, getCardMarginData, doSaveDetailPagesize, getCubeLikeInfo, saveCubeLikeInfo, docustompage } from '../../apis/card';
import ModeExcel, { DetailProps } from './ModeExcel';
import { guid, checkHref } from '../../util/typeUtil';
import { getLayoutFields, MainFieldProps, SelectOptionProps } from '../form';
import CubeForm from '../form/form';
import CubeTrigger from './cube-trigger';
import CardTab from "./CardTab"
import ShareStore from '../list/ShareStore';
import MapStore from './MapStore';
import CustomDialogStore from './CustomDialog';
import Search from '../list';
import LogListStore from '../list/LogListStore';
import { WeaLocaleProvider, WeaTools, WeaInputLocale } from "ecCom";
import API from '../../apis';
import * as WaterMark from '../../pages/watermark';
import { modeForm } from '../../util/excelUtil';
import { any } from 'prop-types';
import { manageScriptContent } from '../../cubeUtil';
import { QuickEditStore, layoutBaseProps } from './quickEditStore';
import { isNumber } from '../../util/typeUtil';
const getCurrentLabel = WeaInputLocale.getCurrentLabel
const getLabel = WeaLocaleProvider.getLabel;

export default class CardStore {
    static isTitleChanged: string;
    @observable parentCard: CardStore;
    @observable card: CardStore;
    @observable query = {};
    @observable layoutType = '0';
    @observable isOreadySubmit = true;

    @observable pageError = false;
    @observable errorMessage = '';

    @observable layoutError = '';

    @observable isexcel: boolean;
    @observable isImportDetail: boolean;
    @observable custompage: string;
    @observable istabinline: boolean;
    @observable isfromTab: boolean;
    @observable windowTitle = '';
    @observable changeDataTime = '';
    @observable datajson = {};

    @observable modeTabKey = {};

    @observable showReply: boolean = false;
    @observable icon = 'icon-coms-ModelingEngine';
    @observable iconBgcolor = "#96358a";
    @observable categorytype = '';

    @observable ifrmaeHeight: number = 0;
    uploadFields: string[] = [];


    @observable isInline: boolean = false;
    @observable isfrontmultlang: 0;


    @observable modeExcel: ModeExcel = new ModeExcel();
    @observable allFields: any = {};
    @observable fieldsProps: any = {};
    @observable cubeForm: CubeForm;
    @observable loading: boolean = false;

    @observable layoutBaseLoading = false;
    @observable fieldsLoading = false;
    @observable isInit = false;
    @observable detailTable: any = {};
    @observable cubeTrigger: CubeTrigger;
    Actions = new Actions(this);
    @observable cardTab = new CardTab(this);
    @observable params: any = {};
    @observable layoutid = '';
    @observable printEdcUrl = '';
    @observable token = '';
    @observable reply: ReplyStore;
    @observable detailImport: DetailImportStore;
    @observable setTabearaActiveKey: any = {};

    @observable share: ShareStore = new ShareStore();
    @observable mapStore: MapStore = new MapStore(this);

    @observable customDialog = new CustomDialogStore();

    @observable isSearchShow: boolean = false;
    @observable isCardShow: boolean = false;
    @observable isInTree: boolean = false;
    @observable isShowReply: boolean = false;
    @observable isLogListShow: boolean = false;
    @observable empowmentType = '';//是否开启临时赋权

    //是否允许点赞和踩
    @observable isallowlike = '';
    @observable likeshowname = '';
    @observable isallowdislike = '';
    @observable dislikeshowname = '';
    @observable likecount: number = 0;
    @observable dislikecount: number = 0;
    @observable likestatus = '';


    @observable base: {
        formId: string,
        modeId: string,
        nondefaultshared: boolean,
        defaultshared: boolean,
        billid: string;
        modeName: string;
        modeTitle: string;
        modeTitleFieldList: any[];  //自定义标题的组成字段
        type: string;
        categoryType: string;
        category: any;
        selectCategory: string;
        showReply: boolean;
        replyposition: Number;
        defaultcontraction: string;
        istagset: string;
        modedatastatus: number;
        fileisdisplay: Number;
    } = {} as any;
    @observable orderbyfield: string = '';
    @observable orderbytype: boolean = false;
    @observable newParamsAdd: any = {};
    @observable scriptCode: any = {};

    @observable waterImg: string = "";
    @observable targetHref: string = "";

    @observable verified = false;
    @observable hasRight = false; //权限
    @observable iconInfo = {
        icon: "icon-coms-ModelingEngine",
        iconColor: "#fff",
        iconBg: "#96358a"
    }
    @observable cardMarginParams: any = {
        padding: {
            top: 30,
            bottom: 30,
            left: 50,
            right: 50,
        }
    }
    @observable variableMap: any = {};
    @observable detailMap: any = {};
    @observable browserPropMap: any = {};

    @observable getEcmeFieldData = any;
    @observable ecmeFieldEventCallBack = any;
    @observable submitParam:any = {};//存储额外的提交参数

    @computed get isShowLoading(): boolean {
        if (this.isSearchShow) {
            return Search.newTable.loading;
        } else if (this.isCardShow) {
            return this.card.loading;
        } else {
            return this.loading;
        }
    }

    @computed get fieldsPropsToShow(): any {
        if (this.isCardShow) {
            return this.card.fieldsProps;
        } else {
            return this.fieldsProps;
        }
    }

    @computed get needSumFields(): string[] {
        return this.cubeTrigger.needSumFields;
    }
    @observable ecmecallBack: any;
    @observable sliderParams = { sliderPercentage: '70', slideModalUrl: "" };
    @observable slideModalVisible: boolean = false;

    @observable showGlobalSpin: any = { //代码块中 控制全局spin
        isShow: 'none',
    };

    secondflag = true; //判断是否需要二次验证
    @observable quickEditStore: QuickEditStore = new QuickEditStore(this);
     /***快速编辑新增 */
    @observable layoutBase: layoutBaseProps;
    reloadParams:any = {};
    @observable  modeTitleFieldArr:any =[]; //用来存放控制标题变化的字段

    getModeTitleFieldFields = (modeTitleFieldArr=[])=>{
        const fieldArr:any = [];
        modeTitleFieldArr.forEach((item:any) => {
            if(item.fieldid){
                fieldArr.push(item.fieldid)
            }
        });
        this.modeTitleFieldArr = fieldArr;
    }

    // 当组成标题的字段发生改变时，重新拼接标题字符串
    @action
    changeModeTitle = (value, fieldName) => {
        /***r如果没有设置字段为标题字段就不要走了 */
        if(this.modeTitleFieldArr.indexOf(fieldName) < 0 ){return }
        const escape2Html = (str) => {
            str = str.replace(/[\r\n]/g, "")
            var arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"', 'hellip': '…' };
            return str.replace(/&(lt|gt|nbsp|amp|quot|hellip);/ig, function (all, t) { return arrEntities[t]; });
        }
        //选择框字段用在模块标题中时 需要转换一下显示名。
        const { fieldhtmltype,fieldtype,options } =this.getFieldProps(fieldName)
        if(fieldhtmltype==5 && fieldtype==2 && value ){
            var val=value.split(",").sort();
            var showname="";
            val.forEach((item) => {
                if(isNumber(item)){
                var itemshowname=options.get(item).showname;
                showname+=" "+itemshowname;
                }
            });
            if(showname != undefined && showname != ''){
                value = showname.substring(1);   
            }
        }
        const newModeTitle: any = [];
        if (this.base.modeTitleFieldList) {
            this.base.modeTitleFieldList.forEach((item) => {
                let val = item.value;
                if (item.inputValue == '1' && item.fieldid == fieldName) {
                    val = item.value = value ? value.toString().replace(/<[^>]+>/g, "") : value;  //当value为富文本框的值时，去除HTML标签，只保留文本内容
                }
                if (val != undefined && val != '') {
                    if (val.startsWith('base64_')) {
                        const Base64 = WeaTools.Base64;
                        val = val.substring(7);
                        val = Base64.decode(val);
                    }
                    val = getCurrentLabel(val);
                }
                val = val ? escape2Html(val) : val;
                newModeTitle.push(val);
            });
            if (_.trim(newModeTitle.join(''))) {  // 当拼接出的标题字段为空时，将modeName作为默认标题展示，而不直接显示空白
                this.base.modeTitle = newModeTitle.join('');
            } else {
                this.base.modeTitle = this.base.modeName;
            }
            if (window.location.href.indexOf('card') > -1 && window.location.href.indexOf('wui/index.html') == -1) { // 仅当为card时，保持windowTitle同步修改
                this.windowTitle = this.base.modeTitle;
            }
        }

    }
    @action
    setIsOreadySubmit(isOreadySubmit) {         //校验只允许提交一次保存
        this.isOreadySubmit = isOreadySubmit;
    }
    @action
    loadReply = () => {
        this.reply = new ReplyStore();
        let p = this.params;
        if (this.base && this.base.replyposition) {
            p = { ...this.params, replyposition: this.base.replyposition };
        }
        this.reply.updateParams(p);
    }
    setRefreshParams = (fieldObj: any) => {
        _.each(fieldObj, (objvalue, fieldid) => {
            if (objvalue.isdetail) {
                _.set(this.allFields, `${fieldid}.order`, null);
            }
        });
    }

    @action
    refreshDetail = (field: string, orderbytype: boolean) => {
        const { detail } = this.getFieldProps(field);
        const datas = this.cubeForm.getDetailInitData(detail);
        const { fieldhtmltype, fieldtype } = _.get(this.allFields, field);
        let _datas: any[] = [];
        if (!orderbytype) { //降序
            if (fieldhtmltype == 1 && fieldtype != 1) {//整数或浮点数
                _datas = datas.sort((a, b) => {
                    a = _.get(a, field);
                    b = _.get(b, field);
                    if (a == '') return -1;
                    if (b == '') return 1;
                    return a - b
                });
            } else {
                _datas = datas.sort((a, b) => _.get(a, field) > _.get(b, field) ? 1 : -1);
            }
        } else { // 升序
            if (fieldhtmltype == 1 && fieldtype != 1) {//整数或浮点数
                _datas = datas.sort((a, b) => {
                    a = _.get(a, field);
                    b = _.get(b, field);
                    if (a == '') return 1;
                    if (b == '') return -1;
                    return b - a
                });
            } else {
                _datas = datas.sort((a, b) => _.get(b, field) > _.get(a, field) ? 1 : -1);
            }
        }
        if (this.cubeForm.has(detail)) {
            this.cubeForm.$(detail).map(r => {
                this.cubeForm.$(detail).del(r.key);
            })
        }
        this.initDetailDatas(_datas, detail);
    }

    getFieldProps = (path: string) => {
        return { ..._.get(this.allFields, path) }
        //return { ..._.get(this.allFields, path), needSum: this.needSumFields.indexOf(path) > -1 }
    }

    /***获取快速编辑的状态 */
    getFieldEditState = (path: string) => {
        return { ..._.get(this.fieldsProps, path) };
    }

    getDetailTable = (path: string): DetailProps => {
        return _.get(this.detailTable, path) || {};
    }

    @action
    addDetailDefaultDatas = () => {   //规则执行完后，判断是否有默认一行，有的话加一行，处理PARM明细表默认值问题
        _.each(this.detailTable, (detail: any) => {
            if (detail.isDefault && this.cubeForm.$(`detail_${detail.orderid}`).values().length === 0) {
                //    this.cubeForm.addRow(detail.orderid);
                if (detail.adddefaultrow != undefined && this.base.type == '1') {//只有新建布局默认新增明细生效
                    for (var i = 0; i < detail.adddefaultrow; i++) {
                        this.cubeForm.addRow(detail.orderid);
                    }
                }
            }
        })
    }


    @action
    getDetailTables = (params: any = this.params) => {
        initDetail(params).then(action(({ status, errorCode, error, detailTable }: any) => {
            if (status == '1') {
                if (_.isEmpty(detailTable)) {
                    this.cubeTrigger.init(params, this.addDetailDefaultDatas).then(() => {
                        if (this.ecmecallBack && typeof this.ecmecallBack == 'function') this.ecmecallBack()
                        try {
                            if (this.params.isecmeview && this.params.isecmeview === "1") {
                                (window as any).parent.ecmeLayoutCache(params.type);
                            }
                        } catch (e) {
                        }

                    });
                }
                // this.isDetailLoaded = true;
                this.detailTable = detailTable;
                const getDetailFieldArr: any = [];
                const detailArr: any = [];
                _.each(detailTable, (detail: any, key) => {
                    _.set(this.modeExcel.details, `detail_${detail.orderid}.detailProps`, detail);
                    if (this.cubeForm.has(key)) {
                        this.cubeForm.$(key).pageSize = detail.detailPageSize || 10;  //更新明细表的分页pagesize
                    }
                    getDetailFieldArr.push(getDetailFields({
                        ...params, tablename: detail.tablename, formId: detail.formId, groupid: detail.orderid - 1
                    }));
                    detailArr.push(detail);
                });
                getDetailFieldArr.length>0 && Promise.all(getDetailFieldArr).then(action((result: any) => {
                    result.map(({ status, errorCode, error, datas, defaultValue, orders }, index) => {
                        if (status !== "1") {
                            message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
                            return;
                        }
                        _.each(orders, (order, fieldid) => {
                            _.set(this.allFields, `field${fieldid}.order`, order === 'desc');
                        });
                        const detailPageSize = Number(detailArr[index].detailPageSize);
                        if (detailArr[index].isPagination) { //如果启动分期，初始化form异步加载
                            this.initDetailDatas(datas.slice(0, detailPageSize), `detail_${detailArr[index].orderid}`, defaultValue);
                            const _this = this;
                            setTimeout(() => {
                                _this.initDetailDatas(datas.slice(detailPageSize), `detail_${detailArr[index].orderid}`, defaultValue, detailPageSize, _this.cubeTrigger.doRowColConsComputed);
                            }, 100)
                        } else {
                            this.initDetailDatas(datas, `detail_${detailArr[index].orderid}`, defaultValue);
                        }
                        _.set(this.detailTable, `${detailArr[index]}.defaultValue`, defaultValue);
                    });
                })).then(() => {
                    this.cubeTrigger.init(params, this.addDetailDefaultDatas).then(() => {
                        if (this.ecmecallBack && typeof this.ecmecallBack == 'function') this.ecmecallBack()
                        try {
                            if (this.params.isecmeview && this.params.isecmeview === "1") {
                                (window as any).parent.ecmeLayoutCache(params.type);
                            }
                        } catch (e) {
                        }

                    });
                })
                try {
                    const that = this;
                    setTimeout(() => {
                        (window as any).checkCustomize = ""; //每次清除这个二次校验得方法
                        $("#custompageCodeArea").append(that.scriptCode.codejs);
                        const uuid = window.location.hash.slice(window.location.hash.lastIndexOf("=") + 1),
                            idname = `#custompageCodeArea-${uuid}`;
                        if ($(idname).length > 0) {
                            $(idname).append(that.scriptCode.codejs);
                        }
                    }, 500)
                } catch (e) {
                }
            } else {
                message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
            }
            this.fieldsLoading = false;
        }))

    }

    @action
    initDetailDatas = (datas: any[], detail: string, defaultValue?: any, startkey = 0, callback?) => {
        if (this.cubeForm) {
            this.cubeForm.initDetailDatas(datas, detail, this.allFields, defaultValue, startkey, callback);
        } else {
            this.initDetailDatas(datas, detail, defaultValue);
        }
        this.doSelectItemChange(); //下拉框联动
    }

    @action
    showDetailImport = () => {
        this.detailImport = new DetailImportStore();
        this.detailImport.initCard = this.init.bind(this, this.params);
        this.detailImport.uploadParams = { isImportDetail: true, ...this.params };
        this.detailImport.modename = this.base.modeName;
        this.detailImport.show();
    }

    @action
    init = (params: any, callback?: Function) => {
        this.clear();
        API.getAppInfoByID({ modeid: params.modeId }).then((data: any) => {
            if (data.status == "1") {
                this.iconInfo = {
                    icon: data.icon || "icon-coms-ModelingEngine",
                    iconColor: data.iconColor || "#fff",
                    iconBg: data.iconBg || "#96358a"
                };
            }
        });
        (this.cubeForm as any) = undefined;
        this.mapStore = new MapStore(this);
        this.modeExcel = new ModeExcel();
        this.cardTab = new CardTab(this);  //qc： 504122  去掉了，需要回归这个一下
        this.isInline = params.istabinline == '1';
        window.changeLoadingState = this.changeLoadingState;
        this.params = params;
        const uuid = guid();
        let _params = { ...params, uuid };
        this.mapStore.showButtons = params.type == '1' || params.type == '2';
        this.loading = true;
        this.isInit = false;
        checkCardRight(_params).then(({ hasRight, ...data }) => {
            if (!hasRight) {
                this.hasRight = false;
                this.verified = true;
                this.isInit = true;
                this.loading = false;
                return
            } else {
                CardStore.isTitleChanged = "0";
                this.hasRight = true;
                this.verified = true;
                let datas: any = [];
                this.getCardMarginData(_params);
                Promise.all([
                    getModeBase(_params),
                    mainFields(_params)
                ]).then(res1 => {
                    datas = res1;
                    if (undefined != datas[1].changeDataTime) {
                        this.changeDataTime = datas[1].changeDataTime;
                    }
                    if (!datas[1].isTitle) {
                        if (datas[0].modeTitle.startsWith('base64_')) {
                            const Base64 = WeaTools.Base64;
                            datas[0].modeTitle = Base64.decode(datas[0].modeTitle.substring(7));
                        }
                        if (!datas[0].modeTitle) {
                            datas[0].modeTitle = datas[0].modeName;
                        }
                        this.windowTitle = datas[0].modeTitle;
                    }
                    if (this.windowTitle != undefined && this.windowTitle != '') {
                        if (this.windowTitle.startsWith('base64_')) {
                            const Base64 = WeaTools.Base64;
                            this.windowTitle = this.windowTitle.substring(7);
                            this.windowTitle = Base64.decode(this.windowTitle);
                        }
                    }
                    this.isfrontmultlang = datas[0]["isfrontmultlang"] || 0;
                    const modedatastatus = datas[0]['modedatastatus'] || 0;
                    this.empowmentType = datas[0]['empowmentType'] || "";
                    this.isallowlike = datas[0]['isallowlike'] || "0";
                    this.likeshowname = datas[0]['likeshowname'] || "";
                    this.isallowdislike = datas[0]['isallowdislike'] || "0";
                    this.dislikeshowname = datas[0]['dislikeshowname'] || "";
                    this.base.defaultcontraction = datas[0]['defaultcontraction'] || "";
                    let billidtemp = datas[0]['billid'] || "";
                    if (billidtemp != undefined && billidtemp != '') {
                        this.params.billid = billidtemp;
                    }
                    if (this.base.billid != undefined && this.base.billid != '') {
                        datas[0]['billid'] = this.base.billid;
                    } else {
                        datas[0]['billid'] = _params.billid;
                    }
                    this.initCardLikeInfo(_params);
                    return layoutBase({ ..._params, modedatastatus: modedatastatus });
                }).then(action((res2) => {
                    datas.push(res2);
                    const { secondPassword } = datas[2] as any;
                    if (secondPassword && this.secondflag) { //开启了二次身份验证
                        this.doSecondaryVirty(params, datas, _params, callback);
                    } else {
                        this.initcardothers(params, datas, _params, callback);
                    }
                }));
            }
        })
    }

    //初始化卡片页面
    initcardothers = (params, datas, _params, callback) => {
        const { status: status0, errorCode: errorCode0, error: error0, modeTitleFieldList,...card } = datas[0] as any;
        const { status, errorCode, error, errorPage, message: msg, datajson, showReply, fields, layoutid, layoutType, printEdcUrl, script, token, detailOpenCustomOrder, custompage, ...newProps } = datas[2] as any;
        const { status: status1, errorCode: errorCode1, error: error1, fields: fields1 } = datas[1] as any;
        if (status0 != '1') {
            message.error(`[${getLabel(127353, "错误") + errorCode0}]:${error0}`);
        } else if (status != '1') {
            message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
        } else if (status1 != '1') {
            message.error(`[${getLabel(127353, "错误") + errorCode1}]:${error1}`);
        } else if (errorPage) {
            message.error(msg);
        } else {
            /****
             * 加个接口判断是不是有e8或者e9布局
             * layoutType == '1' e8
             */
            if (layoutType == '1') {
                //暂时先这样做后续修改为将解析的html布局内容直接以innerHtml的方式嵌入新页面
                const { query } = window.weaHistory.getCurrentLocation();
                const queryStr = _.keys(_.mapKeys(query, (value, key) => {
                    return `${key}=${value}`;
                })).join("&");
                if (params.type == '4') {
                    window.location.href = `/formmode/view/FormModePrint.jsp?${queryStr}`;
                } else {
                    const doThemeAction = (window as any).doThemeAction;
                    if (typeof doThemeAction == 'function') {
                        (window as any).doThemeAction('onLoadMain', {
                            url: `/formmode/view/AddFormMode.jsp?${queryStr}`,
                            target: 'mainFrame'
                        })
                    } else {
                        window.location.href = `/formmode/view/AddFormMode.jsp?${queryStr}`;
                    }
                }
                return;
            }
            // if (this.params && !this.params['isbatchprint']) {
            //     /**
            //      * //这里打印模板的时候，有的方法需要先执行下，但是直接都执行了可能会有坑，
            //      * 暂时不知道会有啥，具体遇见再看，插入代码快控制radio样式加的
            //      */
            //     if (params.type == '4') {
            //         try {
            //             $("#custompageCodeArea").html("").append(script);
            //         } catch (error) {}
            //     }
            // }
            this.modeExcel.isDragulaMap = detailOpenCustomOrder || {};
            if (custompage && custompage != "") {
                this.docustompage(custompage, params);
            }
            this.addCode(script);
            this.getModeTitleFieldFields(modeTitleFieldList);
            this.base = { ...card,modeTitleFieldList } as any;
            this.token = token;
            this.layoutBase = { ...newProps } as any;
            /*不关联模块的浏览框解决*/
            this.params = { billid: card.billid, ...this.params, modeId: card.modeId };
            _params = { ..._params, modeId: card.modeId };

            this.cubeTrigger = new CubeTrigger(this);
            this.loadReply();
            if (callback && _.isFunction(callback)) {
                if (this.params.isecme && this.params.isecme === "1") {
                    this.ecmecallBack = callback
                } else {
                    callback();
                }
            }
            this.layoutid = layoutid;
            if (params.type == '0') {
                this.printEdcUrl = printEdcUrl;
            }
            this.scriptCode = script;
            const newParams = { ..._params, layoutid, modedatastatus: card.modedatastatus || "" };
            // this.newParamsAdd = newParams;
            this.cardTab.init(newParams);
            this.getDetailTables(newParams);
            this.showReply = showReply;
            this.allFields = fields1;
            //this.setRefreshParams(fields1);
            const uploadFields: string[] = [];
            _.each(fields1, (f: MainFieldProps, k: string) => {
                if (f.fieldhtmltype == '6') {
                    uploadFields.push(k);
                }
            });
            this.uploadFields = uploadFields;
            this.modeExcel.init(datajson, params.type);
            this.reloadParams = { ...newParams, datajson };
            this.cubeForm = getLayoutFields(fields1, this, { ...newParams, datajson }); //初始化card form
            // this.base = {...card} as any;
            this.fieldsProps = fields;
            this.isInit = true;
            this.doSelectItemChange();
            this.getWaterMarkImg(card.modeId);
            // setTimeout(() => {
            // this.cubeTrigger.init(newParams, this.addDetailDefaultDatas);
            // }, 300)
            if (this.params && !this.params['isbatchprint']) {
                if (params.type == '4') {
                    $("body").addClass("printBody");
                    setTimeout(() => {
                        (window as any).print();
                    }, 3000)
                }
            }
        }
        this.loading = false;
        CardStore.isTitleChanged = "1";
    }


    addCode = (scriptCode) => {
        try {
            $("#custompageCodeArea").html("");
            $("#custompageCodeArea").append(scriptCode.codecss);
            const uuid = window.location.hash.slice(window.location.hash.lastIndexOf("=") + 1),
                idname = `#custompageCodeArea-${uuid}`;
            if ($(idname).length > 0) {
                $(idname).html("");
                $(idname).append(scriptCode.codecss);
            }

        } catch (e) { }
    }

    @action
    docustompage = (address: string, params: any) => {
        params["__address__"] = address;
        params["formmodeid"] = params.modeId
        params["formid"] = params.formId
        docustompage(params).then((result: any) => {
            setTimeout(() => {
                try {
                    const tempstr = manageScriptContent(result);
                    $("#custompageCodeArea").append(`<div class="_custom_script_">${tempstr}</div>`);
                } catch (e) {
                    if ((window as any).console) { console.log(e); }
                }
            }, 100);
        })
    }


    @action
    getWaterMarkImg = (id: string) => {
        const pagetype = this.base.type;
        getWaterMarkImg({ modeid: id }).then((data: any) => {
            if (data.status == '1') {
                if (data.isWatermark == 1 && (pagetype == '3' || pagetype == '4' || pagetype == '0')) { //开启,显示，打印，监控布局
                    if (data.waterType == "0") {   //文字
                        this.waterImg = WaterMark.__waterDocumentSvg({ ...data });
                    } else {
                        this.waterImg = "data:image/png;base64," + data.img; //data:image/png;base64,
                    }
                } else {
                    this.waterImg = "";
                }
            } else {
                message.error(`${getLabel(127353, '错误')}`);
            }
        })
    }
    getQuery = (href: string) => {
        const lastofnum = href.lastIndexOf('?');
        href = href.slice(lastofnum);
        const query = href.split('?')[1];
        const querys = query.split("&");
        const queryObj: any = {};
        // _.set(queryObj, url, url)
        querys.map(q => {
            const [name, value] = q.split("=");
            _.set(queryObj, name, value);
        });
        return queryObj;
    }
    @action
    showSearch = (href: string) => {
        this.isSearchShow = true;
        Search.reloadSearch(this.getQuery(href), this);
    }
    @action
    showCard = (href: string) => {
        this.isCardShow = true;
        if (!this.card) {
            this.card = new CardStore();
        }
        this.card.targetHref = href;
        this.card.reloadSearch(this.getQuery(href), this);
    }
    @action
    innerCardInit = (param = {}) => {
        this.reloadSearch(param, this);
    }
    @action
    showInnerReply = (href: string) => {
        this.isShowReply = true;
    }

    @action
    showInnerLogList = (href: string) => {
        this.isLogListShow = true;
        LogListStore.updateParams(this.getQuery(href));
    }


    @action
    doSelectItemChange = (newRow?) => {
        let detailField: any = {}
        for (let i in this.allFields) {
            if (this.allFields[i].isdetail == true) {
                detailField[i] = this.allFields[i]
            }
        }
        _.each(newRow ? detailField : this.allFields, (field: MainFieldProps, key: string) => {
            const changeSelectItem = (form: any, field: MainFieldProps, key: string, changeFieldId: string, isChangeValue?) => {
                if (form.has(key) && field.options && form.has(changeFieldId)) {
                    const value = form.$(key).getValue();
                    let filterOptions: SelectOptionProps[] = [];
                    field.options.slice().map((option: SelectOptionProps) => {
                        if (option.key == value) {
                            const { options } = this.getFieldProps(changeFieldId);
                            filterOptions = options.filter((opt: SelectOptionProps) => option.childitemid.indexOf(opt.key) > -1);
                        }
                    })
                    const changeField = form.$(changeFieldId);
                    changeField.set("options", filterOptions.filter(d => d.cancel != '1'));
                    if (filterOptions != undefined && !isChangeValue) {
                        const filterOptions_KeyArr = filterOptions.map(d => d.key);
                        const defaultOptions_KeyArr = filterOptions.filter(d => d.isdefault == 'y');
                        changeField.getValue().split(',').forEach(item => {
                            if (filterOptions_KeyArr.indexOf(item) < 0) {
                                const v = defaultOptions_KeyArr.length > 0 ? defaultOptions_KeyArr[0]['key'] : '';
                                changeField.onChange(v);
                            }
                        })
                        // changeField.onChange('');
                    }
                }
            }
            const doSelectItem = (field: MainFieldProps, key: string, index?: string, isChangeValue?) => {
                const { isdetail, detail } = this.getFieldProps(key);
                let changeFieldId = `field${field.childfieldid}`;
                if (isdetail) {
                    if (this.cubeForm.has(detail)) {
                        this.cubeForm.$(detail).map(row => {
                            if (index && row.key != index) {
                                return null;
                            }
                            changeSelectItem(row, field, key, changeFieldId, isChangeValue);
                        })
                    }
                } else {
                    changeSelectItem(this.cubeForm, field, key, changeFieldId, isChangeValue);
                }
            }
            if (field.fieldhtmltype == '5' && field.childfieldid && field.childfieldid != '-1' && field.options && _.isArray(field.options.slice())) {
                // 新建布局和点击新增明细时选择框才联动出默认值,其余情况只更新option
                const isChangeValue = this.base.type == '1' && !newRow ? '' : 1
                doSelectItem(field, key, '', isChangeValue);
                this.cubeTrigger.addOnChange(key, (index?: string) => {
                    doSelectItem({ ...field }, key, index);
                });
            }
        })
    }


    @action
    changeLoadingState = (bool: boolean = false) => {
        this.loading = bool;
        const tabcontentframe = _.get(window.frames, 'tabcontentframe');
        if (tabcontentframe) {
            $('#tabcontentframe').height(Math.max($(window.frames['tabcontentframe'].document).find('.coms-mode-docker').height(), $(".cube-card-iframe").height() - 5));
        }
    }


    @computed
    get docCategroy(): { mainCategory: string, subCategory: string, secCategory: string, maxUploadSize: number, msg: string } {
        if (this.base.categoryType == '1') {
            const field = `field${this.base.selectCategory}`;
            const { options = [], fieldlabel } = this.getFieldProps(field);
            if (this.cubeForm.has(field)) {
                const value = this.cubeForm.$(field).getValue();
                const selectOpt = options.filter(opt => opt.key == value);
                if (selectOpt.length > 0) {
                    const category: any = {};
                    const opt: SelectOptionProps = selectOpt[0];
                    if (opt.docCategory) {
                        const [mainCategory, subCategory, secCategory] = opt.docCategory.split(",");
                        _.set(category, 'mainCategory', mainCategory);
                        _.set(category, 'subCategory', subCategory);
                        _.set(category, 'secCategory', secCategory);
                        _.set(category, 'maxUploadSize', opt.maxUploadSize > 0 ? opt.maxUploadSize : 5)
                    }
                    return category;
                }
            }
            if (this.base.type == "1" || this.base.type == "2" || this.base.type == "0") {
                return { msg: `${getLabel(125389, '请先选择') + fieldlabel}` } as any;
            } else {
                return { msg: "" } as any;
            }

        } else {
            return this.base.category || {};
        }
    }

    chooseDocCategroy = (selectFieldId) => {
        const field = `field${selectFieldId}`;
        const { options = [], fieldlabel } = this.getFieldProps(field);
        if (this.cubeForm.has(field)) {
            const value = this.cubeForm.$(field).getValue();
            const selectOpt = options.filter(opt => opt.key == value);
            if (selectOpt.length > 0) {
                const category: any = {};
                const opt: SelectOptionProps = selectOpt[0];
                if (opt.docCategory) {
                    const [mainCategory, subCategory, secCategory] = opt.docCategory.split(",");
                    _.set(category, 'mainCategory', mainCategory);
                    _.set(category, 'subCategory', subCategory);
                    _.set(category, 'secCategory', secCategory);
                    _.set(category, 'maxUploadSize', opt.maxUploadSize > 0 ? opt.maxUploadSize : 5)
                }
                return category;
            }
        }
        return { msg: `${getLabel(125389, '请先选择') + fieldlabel}` } as any;
    }


    getDataParams = (fieldid: string, form: any) => {
        const currenttime = new Date().getTime();
        const fields: any = { currenttime };
        this.cubeForm.map(f => {
            if (f.key.startsWith('field')) {
                const { fieldname } = this.getFieldProps(f.key);
                _.set(fields, `${fieldname}_${currenttime}`, f.getValue());
            }
        });

        const { isdetail } = this.getFieldProps(fieldid);
        if (isdetail) {
            form.map(f => {
                if (f.key.startsWith('field')) {
                    const { fieldname, detailtable } = this.getFieldProps(f.key);
                    fields[`${detailtable}_${fieldname}_${currenttime}`] = f.getValue();
                }
            })
        }
        return fields;
    }

    getDataParamsForSql = (fieldid: string, form: any, sqlNeedFieldKey: object) => {
        const currenttime = new Date().getTime();
        const fields: any = { currenttime };
        const that = this;
        _.forEach(sqlNeedFieldKey, function (value, sql) {
            if (_.parseInt(sql) % 2 === 0) {
                that.cubeForm.map(f => {
                    const { fieldname } = that.getFieldProps(f.key);
                    if (f.key.startsWith('field') && fieldname.toLowerCase() === value) {
                        _.set(fields, `${fieldname}_${currenttime}`, f.getValue());
                    }
                });
            } else {
                const { isdetail } = that.getFieldProps(fieldid);
                if (isdetail) {
                    form.map(f => {
                        const { fieldname, detailtable } = that.getFieldProps(f.key);
                        if (f.key.startsWith('field') && fieldname.toLowerCase() === value) {
                            fields[`${detailtable}_${fieldname}_${currenttime}`] = f.getValue();
                        }
                    })
                }
            }
        });
        return fields;
    }

    @action
    update = (param: any) => {
        for (let key in param) {
            this[key] = param[key]
        }
    }

    @action
    reloadSearch = (params: any, card?: CardStore) => {
        if (card) {
            this.parentCard = card;
        }
        this.init(params);

    }
    @action
    updateParams = (params: any) => {
        //若链接传有同名参数则只取第一个参数值
        let keys = _.keys(params);
        for (let i = 0; i < keys.length; i++) {
            if (params[keys[i]].constructor == Array) {
                params[keys[i]] = params[keys[i]][0];
            }
        }
        //若链接传有同名参数则只取第一个参数值
        let temp = !_.isEqual(toJS(this.params), params);
        this.params = params;
        if (temp) {
            this.reloadSearch(params);
        }
    }

    setBrowserProps = (fieldid, params = {}) => {
        if (!_.isEmpty(params)) {

            _.set(this.allFields, `${fieldid}.browserProps.dataParams`, { ...this.allFields.fieldid.browserProps.dataParams, ...params });
            return;
        }
    }

    @computed get fieldNameMap() {
        let nameMap = observable.map ? observable.map({}) : asMap({});
        !_.isEmpty(this.allFields) && _.forIn(this.allFields, (v, k) => {
            if (v.fieldname) {
                if (v.isdetail) {  //明细表
                    nameMap.set(`${v.detail}.${v.fieldname.toUpperCase()}`, v.fieldid);
                } else {
                    nameMap.set(`${'main'}.${v.fieldname.toUpperCase()}`, v.fieldid);
                }
            }
        });
        return nameMap;
    }

    @action
    clear = () => {
        this.isSearchShow = false;
        this.isCardShow = false;
        this.isInTree = false;
        this.isShowReply = false;
        this.isLogListShow = false;
        modeForm.__propertyChangeFnObj = {};
        modeForm.__detailFieldChangeFnObj = {};
        modeForm.actionFnList = {};
        this.scriptCode = {};
        this.isOreadySubmit = true;
        this.sliderParams = { sliderPercentage: '70', slideModalUrl: "" };
        this.base.billid = '';
        this.submitParam = {};
    }
    @action
    getCardMarginData = (param) => {
        getCardMarginData(param).then((data: any) => {
            if (data.status == "1") {
                const res: any = data.datas;
                const type = res.type || "0";
                let padding: any = {};
                if (type == "0") {  //标准
                    padding = {
                        top: 30,
                        bottom: 30,
                        left: 50,
                        right: 50,
                    }
                } else if (type == "1") {  //无边距
                    padding = {
                        top: 0,
                        bottom: 0,
                        left: 0,
                        right: 0,
                    }
                } else {   //自定义边距
                    padding = {
                        top: res.top,
                        bottom: res.bottom,
                        left: res.left,
                        right: res.right,
                    }
                }
                this.cardMarginParams = { padding: padding }
            } else {
                message.error(`${getLabel(127353, "错误")} :${data.error}`);
            }
        });
    }

    @action
    saveDetailPageSize = (size, detail: string) => {
        const detail_num = detail.split('_')[1];
        const params = {
            layoutid: this.layoutid,
            modeId: this.base.modeId,
            type: this.base.type,
            modedatastatus: this.base.modedatastatus,
            detailPageSize: size,
            detail_num: detail_num,
            billid: this.base.billid
        }
        doSaveDetailPagesize(params).then(data => {
        });
    }

    @action
    reloadCard = (obj = {}) => {
        const params = { ...this.params, ...obj };
        this.init(params);
    }

    @action('批量控制变量区')
    batchControlVariableMap(obj = {}) {
        const newMap: any = { ...this.variableMap };
        _.forEach(obj, (v, k) => {
            newMap[k] = v;
        })
        this.variableMap = newMap;
    }

    @action('控制明细行属性对象')
    controlDetailRowAttr = (detailMark, obj = {}) => {
        const newMap: any = { ...this.detailMap };
        if (!newMap[detailMark]) {
            newMap[detailMark] = {};
        }
        _.forEach(obj, (v, k) => {
            newMap[detailMark][k] = v;
            if(v['disableCheck'] && v['disableCheck'] == true){
                this.cubeForm.controlDetailCheck(detailMark,k,false)
            }
        })
        this.detailMap = newMap;
    }

    @action('控制浏览按钮属性覆盖')
    controlBrowserProp = (fieldMark: string, obj = {}) => {
        const newMap: any = { ...this.browserPropMap };
        if (!newMap[fieldMark]) {
            newMap[fieldMark] = {};
        }
        newMap[fieldMark] = obj;
        this.browserPropMap = newMap;
    }

    initCardLikeInfo(_params) {

        getCubeLikeInfo(_params).then(action((data: any) => {
            if (data.status == '1') {
                this.likecount = data.likecount || 0;
                this.dislikecount = data.dislikecount || 0;
                this.likestatus = data.likestatus || '0';
            } else {
                message.error(`${getLabel(127353, '错误')}`);
            }
        }))
    }

    likeOrdislike(key) {
        saveCubeLikeInfo({ modeid: this.base.modeId, billid: this.params.billid, status: key }).then(action((data: any) => {
            if (data.status == '1') {
                if (data.issuccess) {
                    let _params = {
                        modeId: this.base.modeId,
                        billid: this.params.billid
                    }
                    this.initCardLikeInfo(_params);
                }
            } else {
                message.error(`${getLabel(127353, '错误')}`);
            }

            try {
                this.cardTab.disabled = false;
                if (window.opener && window.opener._table && window.opener._table.reLoad) {
                    window.opener._table.reLoad();
                } else if (window.opener && window.opener.cubeStore) {
                    window.opener.cubeStore.Search.refresh();
                } else if (this.params && this.params.viewfrom) {
                    if (this.params.viewfrom == 'fromsearchlist') { //查询列表的 iframe 链接过来的卡片,保存之后刷新列表 
                        (window as any).parent.cubeStore.Search.refresh();
                    }
                }
            } catch (e) {
            }
        }))
    }

    @action
    showSlideModal = (bool, url, percentage = '70') => {
        url = replaceE8Url(url);
        url = url.replace(/&_key=\w{1,10}&/g, '&');//去掉用户配置多加的key
        url = checkHref(url);
        if (bool) {
            this.sliderParams = {
                slideModalUrl: url,
                sliderPercentage: percentage
            }
        } else {

        }
        this.slideModalVisible = bool;
        //weaTop层级问题,列表内嵌卡片滑出头部被遮盖了
        if (bool) {
            $('.wea-new-top-req-wapper .wea-new-top-req').css({ zIndex: 0 });
        } else {
            $('.wea-new-top-req-wapper .wea-new-top-req').css({ zIndex: 1 });
        }
    }

    //二次密码验证
    @action
    doSecondaryVirty = (params, datas, _params, callback) => {
        const { getLabel } = WeaLocaleProvider;
        const { layoutid } = datas[2] as any;
        const url = `/spa/hrm/index_mobx.html#/main/hrmSingle/secondaryVerify/30`;
        const onSecondaryCancel = () => {

        }

        const onCallbackHandle = f => {
            if (f == 'success') {
                API.updateFreeSecretTime({ layoutid: layoutid }).then((data: any) => {
                    if (data.result) {
                        this.reloadCard(params);
                        this.secondflag = false;
                    } else {
                        message.error(data.message);
                    }
                });

            }

        }
        const showSecondaryVirty = async () => {
            API.modeSecondaryVerify({ layoutid: layoutid }).then((data: any) => {
                if (data.status == '1') {
                    if (data.isNeedSecondPwdVerify) {
                        this.hasRight = false;
                        this.verified = true;
                        this.isInit = true;
                        this.loading = false;
                        const style = { 'width': 600, 'height': 200 };
                        const secondaryVrifyDialog = WeaTools.createDialog({ moduleName: 'hrm', title: getLabel(501195, '身份验证'), url, style, callback: onCallbackHandle, onSecondaryCancel });
                        secondaryVrifyDialog.show();
                    } else {
                        this.initcardothers(params, datas, _params, callback);
                    }
                } else {
                    message.error(data.message);
                }
            });
        }
        showSecondaryVirty();
    }

    @action
    getDetailFormValues = (form) => {
        return form && form.values()
    }

    reloadCardDatas = () => {
        mainFields({ ...this.params, uuid: guid() }).then(action((res: any) => {
            const { status: status1, errorCode: errorCode1, error: error1, fields: fields1 } = res;
            if (status1 != '1') {
                message.error(`[${getLabel(127353, "错误") + errorCode1}]:${error1}`);
            } else {
                if (undefined != res.changeDataTime) {
                    this.changeDataTime = res.changeDataTime;
                }
                this.cubeTrigger = new CubeTrigger(this);
                this.getDetailTables({...this.reloadParams,datajson:''});
                this.allFields = fields1;
                //this.setRefreshParams(fields1);
                const uploadFields: string[] = [];
                _.each(fields1, (f: MainFieldProps, k: string) => {
                    if (f.fieldhtmltype == '6') {
                        uploadFields.push(k);
                    }
                });
                this.uploadFields = uploadFields;
                this.cubeForm = getLayoutFields(fields1, this, { ...this.reloadParams }); //初始化card form
            }

        }))
    }

    @action   //改变提交参数
    changeSubmitParam = (param = {}) => {
        this.submitParam = { ...this.submitParam, ...param };
    }
}
